<template>
  <el-dialog
    :title="{ add: '新增部门', edit: '编辑部门' }[mode]"
    width="50%"
    :visible.sync="isShow"
    @close="closeEvent"
  >
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option
            v-for="item in managerList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="cancelEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartments,
  companyDepartmentPut
} from '@/api/department.js'
export default {
  props: ['initList'],
  data () {
    return {
      mode: 'add',
      isShow: false,
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      managerList: [],
      item: '', // 当前点击项数据
      rules: {
        name: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            min: 1,
            max: 50,
            message: '请输入1-50个字符',
            trigger: 'change'
          },
          // 自定义规则： 排查添加项中不能添加与子集同名的
          // 先拿到这里所有的树形列表数据,通过点前点击项的ID可以找出它的子集,判断和当前输入项是否同名
          {
            validator: (rule, value, callback) => {
              // 找出点击项子集
              let resultArr = []
              if (this.mode === 'add') {
                resultArr = this.initList.filter(i => {
                  if (i.pid === this.item.id) {
                    return true
                  }
                })
              } else if (this.mode === 'edit') {
                resultArr = this.initList.filter(i => {
                  if (i.pid === this.item.pid && i.id !== this.item.id) {
                    return true
                  }
                })
              }

              const bol = resultArr.some(i => {
                return i.name === value
              })
              bol
                ? callback(new Error('请不要输入重复的名称：' + value))
                : callback()
            }
          }
        ],
        code: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            min: 1,
            max: 50,
            message: '请输入1-50个字符',
            trigger: 'change'
          },
          {
            // 和所有数据验证code编码
            validator: (rule, value, callback) => {
              let bol = false
              if (this.mode === 'add') {
                bol = this.initList.some(i => {
                  return i.code === value
                })
              } else if (this.mode === 'edit') {
                bol = this.initList.some(i => {
                  return i.code === value && i.id !== this.item.id
                })
              }
              bol
                ? callback(new Error('请不要输入重复的编码' + value))
                : callback()
            }
          }
        ],
        manager: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ],
        introduce: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            min: 1,
            max: 50,
            message: '请输入1-50个字符',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    // isShow: {
    //   handler (newVal) {
    //     console.log(123)
    //     if (!newVal) {
    //       this.$refs.form.resetFields()
    //     }
    //   }
    // }
  },
  mounted () {
    // 触发兄弟组件传值打开弹框
    this.$bus.$on('addEvent', (show, item, mode) => {
      this.isShow = show
      this.item = item
      this.mode = mode
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy () {
    this.$bus.$off('addEvent')
  },
  methods: {
    closeEvent () {
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    },
    cancelEvent () {
      // 取消事件
      this.isShow = false
    },
    async focusEvent () {
      // 有数据就不调用接口了
      if (this.managerList.length == 0) {
        const res = await sysUserSimple()
        // console.log(res)
        this.managerList = res.data
      }
    },
    // 确定事件
    submit () {
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await companyDepartments(this.form)
            this.$message.success('添加成功')
          } else if (this.mode === 'edit') {
            await companyDepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          this.isShow = false
          // 刷新父级列表数据
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style></style>
